/*
 * jxUtils Project (2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxUtils.file;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxUtils
 * @package org.jxUtils.file
 * @date 22/07/2014 - 19:59:37
 * @see http://www.guj.com.br/java/67639-comparando-arquivos
 */
final class FindDuplicateFiles {
	
	private static final String MESSAGE_DIGEST = "SHA-512";
	
	private final MessageDigest digest;
	
	/**
	 * @throws NoSuchAlgorithmException
	 */
	public FindDuplicateFiles() throws NoSuchAlgorithmException {
	
		digest = MessageDigest.getInstance(MESSAGE_DIGEST);
	}
	
	/**
	 * @param file
	 * @return digest
	 * @throws IOException
	 */
	private String getDigest(final File file) throws IOException {
	
		digest.reset();
		
		final DigestInputStream digestInputStream = new DigestInputStream(new FileInputStream(file), digest);
		
		final byte[] buffer = new byte[1024];

		// 
		while(digestInputStream.read(buffer) > 0) {
			// do
		}
		
		digestInputStream.close();
		
		return toHex(digest.digest());
	}
	
	/**
	 * @param files
	 * @param directory
	 * @param fileFilter
	 */
	private void recursiveFind(final List<File> files, final File directory, final FileFilter fileFilter) {
	
		final File[] filesAux = directory.listFiles(fileFilter);
		
		//
		if(filesAux != null) {

			// 
			for(final File file : filesAux) {

				// 
				if(file.isDirectory()) {
					
					recursiveFind(files, file, fileFilter);
					
				}else {
					
					files.add(file);
				}
			}
		}
	}
	
	/**
	 * @param bytes
	 * @return bytes in Hexadecimal
	 */
	private String toHex(final byte[] bytes) {
	
		final StringBuilder ret = new StringBuilder();
		
		//
		for(final byte b : bytes) {
			
			ret.append(String.format("%02X", b & 0xFF));
		}
		
		return ret.toString();
	}
	
	/**
	 * @param directory
	 * @return {@code Map<Digest, List<File>>}
	 * @throws IOException
	 */
	public Map<String, List<File>> getDuplicateFiles(final File directory) throws IOException {
	
		return getDuplicateFiles(directory, null);
	}
	
	/**
	 * @param directory
	 * @param fileFilter
	 * @return {@code Map<Digest, List<File>>}
	 * @throws IOException
	 */
	public Map<String, List<File>> getDuplicateFiles(final File directory, final FileFilter fileFilter) throws IOException {
	
		final List<File> files = new ArrayList<File>();
		
		recursiveFind(files, directory, fileFilter);
		
		return getDuplicateFiles(files);
	}
	
	/**
	 * @param files
	 * @return {@code Map<Digest, List<File>>}
	 * @throws IOException
	 */
	public Map<String, List<File>> getDuplicateFiles(final List<File> files) throws IOException {
	
		final SortedMap<String, List<File>> filesByDigest = new TreeMap<String, List<File>>();
		
		//
		for(final File file : files) {
			
			final String hexDigest = getDigest(file);
			
			List<File> filesWithEqualsDigest = filesByDigest.get(hexDigest);
			
			//
			if(filesWithEqualsDigest == null) {
				
				filesByDigest.put(hexDigest, filesWithEqualsDigest = new ArrayList<File>());
			}
			
			filesWithEqualsDigest.add(file);
		}
		
		final Map<String, List<File>> digestFiles = new HashMap<>();
		
		//
		for(final Map.Entry<String, List<File>> entry : filesByDigest.entrySet()) {
			
			final String digest = entry.getKey();
			
			final List<File> filesWithEqualsDigest = entry.getValue();
			
			//
			if(filesWithEqualsDigest.size() > 1) {
				
				digestFiles.put(digest, filesWithEqualsDigest);
			}
		}
		
		return digestFiles;
	}
}
